package com.example.demo.Controller;

import com.example.demo.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.*;

@Controller
public class FormController {
    @RequestMapping("/form")
    public String form(Model model) {
        setConstant(model);
        User user = new User();
        user.setName("小明");
        user.setSex(1);
        user.setMyColors(new String[]{"white", "black"});
        model.addAttribute("user", user);
        return "form";
    }

    @PostMapping("/submit")
    public String submit(@ModelAttribute User user, Model model) {
        setConstant(model);
        model.addAttribute("user", user);
        System.out.println("姓名：" + user.getName());
        System.out.println("性别：" + (user.getSex() == 1 ? "男" : "女"));
        System.out.println("喜欢的颜色：" + Arrays.toString(user.getMyColors()));

        List<User> list = new ArrayList<User>();
        User b1 = new User();
        b1.setName("admin");
        b1.setSex(1);
        String[] color = {"red", "blue"};
        b1.setMyColors(color);
        list.add(b1);
        list.add(user);
        model.addAttribute("users", list);
        return "list";
    }

    private void setConstant(Model model) {
        Map<String, Object> sexes = new HashMap<String, Object>();
        sexes.put("男", 1);
        sexes.put("女", 0);
        model.addAttribute("sexes", sexes);
        String[] colors = new String[]{"red", "white", "black"};
        model.addAttribute("colors", colors);
    }
}